﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iAnywhere.Data.SQLAnywhere;
using Oracle.DataAccess.Client;
using System.Configuration;
using Syncer;
using System.Globalization;

namespace SybaseTest
{
    class Nd_Performance_Collector
    {

        static void Main(string[] args)
        {
            Log.OpenLog();
            string bppmConn = string.Empty;
            foreach (var bppmConnKey in ConfigurationManager.AppSettings.Keys)
            {
                if (bppmConnKey.ToString() == "unify") continue; //skip unify

                bppmConn = ConfigurationManager.AppSettings[bppmConnKey.ToString()];

                if (string.IsNullOrEmpty(bppmConn)) //skip empty value
                {
                    Console.WriteLine("The value of " + bppmConnKey + " is empty, skip it.");
                    continue;
                }

                try
                {
                    // LoadDeviceTable(bppmConn);

                }
                catch (Exception ex)
                {
                    Log.Exception("", ex);
                }
            }




            gmtTimeEntity gte = GetGMTDateTime();
            long fromtime = gte.fromtime;
            long totime = gte.totime;

            //LoadPerformanceTable(fromtime, totime, bppmConn);
            Loadt_TmartAvailability(fromtime, totime, bppmConn);
        }



        static gmtTimeEntity GetGMTDateTime()
        {
            Log.Info("begin to get GMT time ...................");
            //DateTime lastDate = DateTime.Now.AddDays(-1);
            //DateTime currentDate = DateTime.Now;

            DateTime lastDate = DateTime.Now.AddDays(-1);
            DateTime currentDate = DateTime.Now;

            String StrLastDate = lastDate.ToShortDateString().ToString();
            String StrCurrentDate = currentDate.ToShortDateString().ToString();

            String StrTimeFrom = StrLastDate + " 00:00:00";
            String StrTimeTo = StrCurrentDate + " 00:00:00";

            DateTime DtTimeFrom = DateTime.Parse(StrTimeFrom);
            DateTime DtTimeTo = DateTime.Parse(StrTimeTo);

            Log.Info("start time for calc is " + DtTimeFrom.ToString());
            Log.Info("end time for calc is " + DtTimeTo.ToString());

            long fromTime = (DtTimeFrom.Ticks - 621355968000000000) / 10000000 - 28800;
            long toTime = (DtTimeTo.Ticks - 621355968000000000) / 10000000 - 28800;

            Log.Info("GMT Start Time is " + fromTime.ToString());
            Log.Info("GMT End Time is " + toTime.ToString());

            return new gmtTimeEntity
            {
                fromtime = fromTime,
                totime = toTime

            };



        }


        /*   static void LoadDeviceTable(string bppmStr)
            {

                using (SAConnection conn = new SAConnection(bppmStr))
                {
                    conn.Open();

                    //删除t_device表
                    string sql = string.Empty;

                    sql = @"drop table t_device";

                    SACommand cmd = new SACommand(sql, conn);
                    SADataReader rd = cmd.ExecuteReader();

               
                    Log.Info("Device Table has been dropped");

                    //创建t_device表
                    sql = string.Empty;

                   sql = @"CREATE 
       TABLE t_device
        (
           MOINSTID INT,
           DEVICENAME VARCHAR(40),
           TYPE VARCHAR(40),
           OBJECT VARCHAR(50),
           INSTNAME VARCHAR(100),
           CreateTime DATETIME
       )";

                    cmd = new SACommand(sql, conn);
                    rd = cmd.ExecuteReader();

                
                    Log.Info("Device Table has been re-build");

                    //重新装载Device Table

                    sql = string.Empty;

                    sql = @"insert into t_device with(NOLOCK)
        select MOINSTID,DEVICENAME,'服务器' type,'unix' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__UNIX_OS_CPU_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'服务器' type,'unix' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__UNIX_OS_MEMORY_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'服务器' type,'unix' object,INSTNAME SubObject,getdate()
        as CreateTime from dba._PATROL__UNIX_OS_STORAGE_FILESYSTEM_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'数据库' type,'oracle' object,substr(INSTNAME,1,(charindex('|',INSTNAME
        )-1)) as INSTNAME,getdate() as CreateTime
        from dba._PATROL__ORACLE_ORACLE_INSTANCE_ORACLE_AVAILABILITY_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'中间件' type,'websphere' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__PMW_MAIN_PMW_NODE_PMW_APPSERVER_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'服务器' type,'windows' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__NT_OS_NT_CPU_CONTAINER_NT_CPU_CFG_VIEW where instname='_Total'
        union all
        select MOINSTID,DEVICENAME,'服务器' type,'windows' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__NT_OS_NT_MEMORY_CFG_VIEW
        union all
        select MOINSTID,DEVICENAME,'服务器' type,'windows' object,INSTNAME,getdate() as CreateTime
        from dba._PATROL__NT_OS_NT_LOGICAL_DISKS_CONTAINER_NT_LOGICAL_DISKS_CFG_VIEW";

                    cmd = new SACommand(sql, conn);
                    rd = cmd.ExecuteReader();

                    Log.Info("Device Table has been re-load");

                    rd.Close();

                    }
                           
                }*/


        //static void LoadPerformanceTable(long fromTime, long toTime, string bppmStr)
        static void Loadt_TmartAvailability(long fromTime, long toTime, string bppmStr)
        {
            //Log.Info("Begin to get performance information ... ... ... ...");
       
            using (SAConnection conn = new SAConnection(bppmStr))
            {
                conn.Open();

                List<ndPerformanceEntity> ndpe = new List<ndPerformanceEntity>();

                ////删除t_TmartAvailability表
                
                
               /*     string sql = string.Empty;

                    sql = @"drop table t_TmartAvailability";

                    SACommand cmd = new SACommand(sql, conn);
                    SADataReader rd = cmd.ExecuteReader();


               Log.Info("t_TmartAvailability Table has been dropped");  */ 

                
                
                ////建立t_TmartAvailability表


                /*   sql = string.Empty;

                sql = @"CREATE TABLE t_TmartAvailability
                    (
                        PROJECT_NAME VARCHAR(256),
                        MOINSTID INT,
                        STATS_AVAILABILITY_AVG VARCHAR(10000),
                        CreateTime DATETIME,
                        FROMTIME INT,
                        TOTIME   INT
                     )";

                cmd = new SACommand(sql, conn);
                rd = cmd.ExecuteReader();


                Log.Info("t_TmartAvailability Table has been created");  */

                //如果已有前一天数据则跳出


                string sql = string.Empty;
                sql = @"select max(FromTime) from t_TmartAvailability with(NOLOCK)";
              //  cmd = new SACommand(sql, conn);
              //  rd = cmd.ExecuteReader();
                SACommand cmd = new SACommand(sql, conn);
                SADataReader rd = cmd.ExecuteReader();
                String earlyTimeStr = string.Empty;
                long earlyTimeLong = 0;
                while (rd.Read())
                {
                    if (rd.FieldCount == 0) return;
                    else
                        earlyTimeStr = rd.GetValue(0).ToString();
                    if (earlyTimeStr == "") earlyTimeStr = "0";
                    else continue;

                }
                earlyTimeLong = Int64.Parse(earlyTimeStr);

                if (earlyTimeLong >= fromTime)
                    return;
                
                /////开始从dba.TMARTTRANSACTIONS_CFG_VIEW中和dba.TMARTTRANSACTIONS_RT_VIEW获取performance数据


             //   string sql = string.Empty;
                sql = string.Empty;
                sql = @"insert into report.t_TmartAvailability (PROJECT_NAME,MOINSTID,STATS_AVAILABILITY_AVG,CreateTime,FROMTIME,TOTIME)
                   select a.PROJECT_NAME,a.MOINSTID,round(avg(b.STATS_AVAILABILITY_AVG),3) as value,getdate() as CreateTime, "
               + fromTime
               + " as fromtime,"
               + toTime
               + " as totime from dba.TMARTTRANSACTIONS_CFG_VIEW a,dba.TMARTTRANSACTIONS_RT_VIEW b with(NOLOCK) where b.fromtime>="
                       + fromTime
                       + " and b.totime <="
                       + toTime
                       + " and a.MOINSTID=b.MOINSTID group by a.PROJECT_NAME,a.MOINSTID";






                Log.Info("Now is loading table t_TmartAvailability");
            
               cmd = new SACommand(sql, conn);
              rd = cmd.ExecuteReader();

             //   SACommand cmd = new SACommand(sql, conn);
             //   SADataReader rd = cmd.ExecuteReader();


                Log.Info("THE report.t_TmartAvailability table have been load");


               // rd.Close();
              

            }
        }
    }
}





                
              /*  while (rd.Read())
                {
                    ndpe.Add(new ndPerformanceEntity
                    {
                        Moinstid = rd["moinstid"].ToString(),
                        Identify = rd["devicename"].ToString(),
                        Parameter = rd["Parameter"].ToString(),
                        ParameterDisplay = rd["ParameterDisplay"].ToString(),
                        value = rd["value"].ToString(),
                        CreateTime = (DateTime)rd["CreateTime"],
                        FromTime = rd["fromtime"].ToString(),
                        ToTime = rd["totime"].ToString(),
                    });
                }   */


                /////开始从_PATROL__UNIX_OS_MEMORY_RT_VIEW中获取performance数据

              /*  sql = @"select a.moinstid, b.devicename,'M
EMFREEMEM' Parameter,'Unix 剩余内存' ParameterDisplay, round(avg(a.MEMFREEMEM_AVG),3) as value,getdate() as CreateTime, "
                + fromTime
                + " as fromtime,"
                + toTime
                + " as totime from dba._PATROL__UNIX_OS_MEMORY_RT_VIEW a,t_device b with(NOLOCK) where a.fromtime>="
                        + fromTime
                        + " and a.totime <="
                        + toTime
                        + " and a.moinstid=b.MOINSTID group by a.moinstid,b.devicename";

                Log.Info("Now is loading table _PATROL__UNIX_OS_MEMORY_RT_VIEW");

                cmd = new SACommand(sql, conn);
                rd = cmd.ExecuteReader();

                
                while (rd.Read())
                {
                    ndpe.Add(new ndPerformanceEntity
                    {
                        Moinstid = rd["moinstid"].ToString(),
                        Identify = rd["devicename"].ToString(),
                        Parameter = rd["Parameter"].ToString(),
                        ParameterDisplay = rd["ParameterDisplay"].ToString(),
                        value = rd["value"].ToString(),
                        CreateTime = (DateTime)rd["CreateTime"],
                        FromTime = rd["fromtime"].ToString(),
                        ToTime = rd["totime"].ToString(),
                    });
                }

                /////开始从_PATROL__UNIX_OS_STORAGE_FILESYSTEM_RT_VIEW中获取performance数据

               sql = string.Empty;

                sql = @"select a.moinstid, b.devicename,'FSCAPACITY' Parameter,'Unix 文件系统使用率' ParameterDisplay, round(avg(a.FSCAPACITY_AVG),3) as value,getdate() as CreateTime, "
                + fromTime
                + " as fromtime,"
                + toTime
                + " as totime from dba._PATROL__UNIX_OS_STORAGE_FILESYSTEM_RT_VIEW a,t_device b with(NOLOCK) where a.fromtime>="
                        + fromTime
                        + " and a.totime <="
                        + toTime
                        + " and a.moinstid=b.MOINSTID group by a.moinstid,b.devicename";

                Log.Info("Now is loading table _PATROL__UNIX_OS_STORAGE_FILESYSTEM_RT_VIEW");

                cmd = new SACommand(sql, conn);
                rd = cmd.ExecuteReader();

                
                while (rd.Read())
                {
                    ndpe.Add(new ndPerformanceEntity
                    {
                        Moinstid = rd["moinstid"].ToString(),
                        Identify = rd["devicename"].ToString(),
                        Parameter = rd["Parameter"].ToString(),
                        ParameterDisplay = rd["ParameterDisplay"].ToString(),
                        value = rd["value"].ToString(),
                        CreateTime = (DateTime)rd["CreateTime"],
                        FromTime = rd["fromtime"].ToString(),
                        ToTime = rd["totime"].ToString(),
                    });
                }  */

               
                //.......................

               /* ///将list中的数据插入到t_performance中

               foreach (var performance in ndpe)
                {
                    try
                    {
                        int ID = 5;
                        String moinstidStr = performance.Moinstid;
                        String ipStr = performance.Identify;
                        String ParameterStr = performance.Parameter;
                        String ParameterDisplayStr = performance.ParameterDisplay;
                        String valueStr = performance.value;
                        DateTime createtimeDt = performance.CreateTime;
                        String fromtimeStr = performance.FromTime;
                        String totimeStr = performance.ToTime;

                        sql = "insert into t_performance values ("
                            + ID + ", '"
                            + moinstidStr + "', '"
                            + ipStr + "', '"
                            + ParameterStr + "', '"
                            + ParameterDisplayStr + "', '"
                            + valueStr + "', '"
                            + createtimeDt.ToString() + "', "
                            + fromtimeStr + ", "
                            + totimeStr + ")";   */


                /*
                        cmd = new SACommand(sql, conn);
                        rd = cmd.ExecuteReader();

                        Log.Info("One performace Inserted.");
                      }
                    catch (Exception ex)
                    {
                        Log.Exception("", ex);
                    }

                }

                rd.Close();
            }
            
            Log.Info("end to test...");
        }
    }
}*/
